﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using AjaxControlToolkit;
using ASPDotNetSamples;
using com.paypal.soap.api;
using System.Data.SqlClient;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Data.Linq;

public partial class OrderDetailNew : System.Web.UI.Page {
    ASPDotNetSamples.BasePage basepage = new ASPDotNetSamples.BasePage();
    protected void Page_Load(object sender, EventArgs e) {
        //setSecureProtocol(true);
        if (!IsPostBack) {
            try {
                System.Web.UI.HtmlControls.HtmlTableRow tdFAQ = (System.Web.UI.HtmlControls.HtmlTableRow)Page.Master.FindControl("tdFAQ");
                tdFAQ.Visible = true;
                if (Request.Cookies["Qty"] != null) {

                    txtQuantity.Text = Request.Cookies["Qty"].Value;
                    Response.Cookies["Qty"].Expires = DateTime.Now.AddDays(-30);
                } else {
                    txtQuantity.Text = "1";
                }
                Session["dtGift"] = null;
                //   txtQuantity.Text = "1";
                Session["Quantity"] = txtQuantity.Text;
                selectProduct();
                expDateMonth.SelectedValue = DateTime.Today.Month.ToString();
                hdnYear.Value = DateTime.Now.Year.ToString();
                hdnMonth.Value = DateTime.Now.Month.ToString();
                expDateYear.Attributes.Add("onchange", "ExpiryValidator()");
                expDateMonth.Attributes.Add("onchange", "ExpiryValidator()");
                Session["username"] = Membership.GetUser().UserName.ToString();
                if (Session["username"] != null) {
                    PerInfo.Visible = false;
                    FillCrdeitAmount();
                }

                // load cc value
                Dictionary<string, string> ccData = Session["CreditCardInfo"] as Dictionary<string, string>;
                if (ccData != null) {
                    firstName.Text = ccData["ccFirstname"];
                    lastName.Text = ccData["ccLastname"];
                    creditCardType.SelectedValue = ccData["ccType"];
                    creditCardNumber.Text = ccData["ccNumber"];
                    expDateMonth.SelectedValue = ccData["ccExpiredMonth"];
                    expDateYear.SelectedValue = ccData["ccExpiredYear"];
                    cvv2Number.Text = ccData["ccVerificationNumber"];
                    address1.Text = ccData["ccAddress1"];
                    address2.Text = ccData["ccAddress2"];
                    city.Text = ccData["ccCity"];
                    state.Value = ccData["ccState"];
                    Zip.Text = ccData["ccZipcode"];
                    Session["CreditCardInfo"] = null;
                }

            } catch {
            }
        }
    }
    public void Button1_OnClick(object o, EventArgs e) {
        panBeforeLogin.Visible = false;
        panLogin.Visible = true;
        divAuthentication.Hide();
    }
    public void setSecureProtocol(bool bSecure) {
        string redirectUrl = null;

        // if we want HTTPS and it is currently HTTP
        if (bSecure && !Request.IsSecureConnection)
            redirectUrl = Request.Url.ToString().Replace("http:", "https:");

        else

            // if we want HTTP and it is currently HTTPS
            if (!bSecure && Request.IsSecureConnection) redirectUrl = Request.Url.ToString().Replace("https:", "http:");

        //else

        // in all other cases we don't need to redirect

        // check if we need to redirect, and if so use redirectUrl to do the job
        if (redirectUrl != null)

            Response.Redirect(redirectUrl);

    }
    public void FillCrdeitAmount() {
        try {
            var credit = new DealesDataContext();
            var Amount = credit.GetCreditAmount(new Guid(Membership.GetUser().ProviderUserKey.ToString()));

            double money = 0.0;
            double referMoney = 0.0;
            tdRefer.Visible = false;
            ViewState["RferAmount"] = money;
            lblCredit.Text = "(0)";
            lblCredit.Visible = false;
            Credit.Visible = false;

            Session["CreditAmount"] = 0;

            foreach (var item in Amount) {
                if (item.amount.ToString() != "0") {
                    tdRefer.Visible = true;
                    money = Convert.ToDouble(item.amount.ToString());
                    if (money > 0) {
                        lblFinalPrice.Visible = true;
                        lblFinalPrice.Text = "<b>Congratulations!</b> You have $" + money + " Zupons credit that <br/>will be applied to this purchase.";
                        lblCredit.Text = "(" + money + ")";
                        lblCredit.Visible = true;
                        Credit.Visible = true;

                        Session["CreditAmount"] = money;
                    }
                    ViewState["RferAmount"] = money;
                    var referAmount = credit.GetReferAmount(new Guid(Membership.GetUser().ProviderUserKey.ToString()));
                    foreach (var items in referAmount) {
                        if (items.ReferAmount != null) {
                            referMoney = Convert.ToDouble(items.ReferAmount.ToString());
                            if ((money - referMoney) == 0.0) {
                                tdRefer.Visible = false;
                                lblFinalPrice.Visible = false;
                                lblCredit.Visible = false;
                                Credit.Visible = false;

                                Session["CreditAmount"] = 0;
                            } else {
                                lblFinalPrice.Visible = true;
                                lblFinalPrice.Text = "<b>Congratulations!</b> You have $" + (money - referMoney) + " Zupons credit that <br/>will be applied to this purchase.";
                                lblCredit.Text = "(" + (money - referMoney) + ")";
                                lblCredit.Visible = true;
                                Credit.Visible = true;

                                Session["CreditAmount"] = money - referMoney;
                            }
                            ViewState["RferAmount"] = (money - referMoney);
                        }
                    }
                }
            }

            double RferAmount = Convert.ToDouble(ViewState["RferAmount"].ToString());
            double TotalPrice = Convert.ToDouble(Session["TotalPrice"].ToString());
            if (TotalPrice > RferAmount) {
                Session["ReferAmount"] = Convert.ToDouble(ViewState["RferAmount"].ToString());
                Session["TotalPrice"] = Convert.ToDouble(Session["TotalPrice"].ToString()) - Convert.ToDouble(ViewState["RferAmount"].ToString());
                lblYourTotal.Text = Session["TotalPrice"].ToString();
                rbtnPaymentType.Enabled = true;
                firstName.Enabled = true;
                lblfirstName.ForeColor = System.Drawing.Color.Black;
                lastName.Enabled = true;
                lbllastName.ForeColor = System.Drawing.Color.Black;
                creditCardType.Enabled = true;
                creditCardNumber.Enabled = true;
                lblcreditCardNumber.ForeColor = System.Drawing.Color.Black;
                expDateMonth.Enabled = true;
                expDateYear.Enabled = true;
                cvv2Number.Enabled = true;
                lblcvv2Number.ForeColor = System.Drawing.Color.Black;
                address1.Enabled = true;
                lbladdress1.ForeColor = System.Drawing.Color.Black;
                address2.Enabled = true;
                lbladdress2.ForeColor = System.Drawing.Color.Black;
                city.Enabled = true;
                lblcity.ForeColor = System.Drawing.Color.Black;
                state.Disabled = false;
                Zip.Enabled = true;
                lblZip.ForeColor = System.Drawing.Color.Black;
                PayButton.Enabled = true;
                //Name.Enabled = true;
                //lblName.ForeColor = System.Drawing.Color.Black;
                //Street.Enabled = true;
                //lblStreet.ForeColor = System.Drawing.Color.Black;
                //paypal_City.Enabled = true;
                //lblpaypal_City.ForeColor = System.Drawing.Color.Black;
                //Select1.Disabled = false;
                //paypal_ZipCode.Enabled = true;
                //lblpaypal_ZipCode.ForeColor = System.Drawing.Color.Black;
                lnkbtnCancel.Enabled = true;
                ViewState["CreditZero"] = null;
                lblcreditCardType.ForeColor = System.Drawing.Color.Black;
                lblExpirationDate.ForeColor = System.Drawing.Color.Black;
                lblstate.ForeColor = System.Drawing.Color.Black;
                PayButton.Attributes.Add("onclick", "return OrderDetailsValidate();");
                lblBillingDetails.ForeColor = System.Drawing.Color.Black;
                lblCCDeatials.ForeColor = System.Drawing.Color.Black;
            } else {
                // Session["ReferAmount"] = Convert.ToDouble(ViewState["RferAmount"].ToString()) - Convert.ToDouble(Session["TotalPrice"].ToString());
                Session["ReferAmount"] = lblPrice.Text;
                lblYourTotal.Text = "0";
                Session["TotalPrice"] = "0";
                rbtnPaymentType.Enabled = false;
                firstName.Enabled = false;
                lblfirstName.ForeColor = System.Drawing.Color.Gray;
                lastName.Enabled = false;
                lbllastName.ForeColor = System.Drawing.Color.Gray;
                creditCardType.Enabled = false;
                lblcreditCardType.ForeColor = System.Drawing.Color.Gray;
                creditCardNumber.Enabled = false;
                lblcreditCardNumber.ForeColor = System.Drawing.Color.Gray;
                lblExpirationDate.ForeColor = System.Drawing.Color.Gray;
                expDateMonth.Enabled = false;
                expDateYear.Enabled = false;
                cvv2Number.Enabled = false;
                lblcvv2Number.ForeColor = System.Drawing.Color.Gray;
                address1.Enabled = false;
                lbladdress1.ForeColor = System.Drawing.Color.Gray;
                address2.Enabled = false;
                lbladdress2.ForeColor = System.Drawing.Color.Gray;
                city.Enabled = false;
                lblcity.ForeColor = System.Drawing.Color.Gray;
                state.Disabled = true;
                lblstate.ForeColor = System.Drawing.Color.Gray;
                Zip.Enabled = false;
                lblZip.ForeColor = System.Drawing.Color.Gray;
                //  PayButton.Enabled = false;
                PayButton.Attributes.Add("onclick", "return true;");
                PayButton.OnClientClick = null;

                //Name.Enabled = false;
                //lblName.ForeColor = System.Drawing.Color.Gray;
                //Street.Enabled = false;
                //lblStreet.ForeColor = System.Drawing.Color.Gray;
                //paypal_City.Enabled = false;
                //lblpaypal_City.ForeColor = System.Drawing.Color.Gray;
                //Select1.Disabled = true;
                //paypal_ZipCode.Enabled = false;
                //lblpaypal_ZipCode.ForeColor = System.Drawing.Color.Gray;
                ViewState["CreditZero"] = 1;
                // lnkbtnCancel.Enabled = false;

                lblBillingDetails.ForeColor = System.Drawing.Color.Gray;
                lblCCDeatials.ForeColor = System.Drawing.Color.Gray;
            }
        } catch {
        }
    }
    public string GetDealID() {
        string CityID;
        string DealID = "0";
        if (Request.Cookies["CityID"] != null) {
            CityID = Request.Cookies["CityID"].Value;
            var sub = new DealesDataContext();
            var getDealID = sub.Select_DealByCityIDNew(Convert.ToInt32(CityID));
            foreach (var item in getDealID) {
                DealID = item.DealID.ToString();

            }
        }
        return DealID;
    }
    public void selectProduct() {

        var a = new DealesDataContext();
        var query = a.SelectProduct_Deal(Convert.ToInt32(Request.QueryString["DealID"].ToString()));
        foreach (var item in query) {
            Session["DealID"] = Request.QueryString["DealID"].ToString();
            lblDescription.Text = item.ShortDescription;
            lblPrice.Text = (System.Math.Round(double.Parse(item.SellPrice.ToString()), 2)).ToString();
            lblTotalPrice.Text = (Convert.ToDouble(lblPrice.Text) * Convert.ToDouble(txtQuantity.Text)).ToString();
            lblYourTotal.Text = System.Math.Round(double.Parse(lblPrice.Text.ToString()), 2).ToString();
            Session["TotalPrice"] = lblTotalPrice.Text;
            Session["Price"] = lblPrice.Text;
            Session["Quantity"] = txtQuantity.Text;
        }
        lblCredit.Text = "(0)";
        lblCredit.Visible = false;
        Credit.Visible = false;

        Session["CreditAmount"] = 0;

        var query2 = new DealesDataContext();
        var CheckQtyQuery = query2.Select_MaxQtyFromDeal(Convert.ToInt32(Request.QueryString["DealID"].ToString()));
        int LimitPerPerson = 0;
        foreach (var j in CheckQtyQuery) {
            LimitPerPerson = Convert.ToInt32(j.limitperperson);
        }
        if (LimitPerPerson == 1) {
            txtQuantity.Enabled = false;
        }
    }
    protected void btnForgetPassword_Click(object sender, EventArgs e) {
        Response.Redirect("PasswordRecovery.aspx");
    }
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) {
        System.Web.UI.WebControls.Login LoginControl1C = LoginControl1;
        if (Membership.ValidateUser(LoginControl1C.UserName, LoginControl1C.Password)) {
            Session["username"] = LoginControl1C.UserName;
            e.Authenticated = true;

            Response.Cookies["Qty"].Value = txtQuantity.Text;
            Response.Cookies["Qty"].Expires = DateTime.Now.AddDays(30);
        } else {
            panLogin.Attributes["style"] = "display:block";
            panBeforeLogin.Attributes["style"] = "display:none";
            e.Authenticated = false;
            Label UserNameLabel = (Label)LoginControl1.FindControl("UserNameLabel");
            UserNameLabel.ForeColor = System.Drawing.Color.Red;
            Label PasswordLabel = (Label)LoginControl1.FindControl("PasswordLabel");
            PasswordLabel.ForeColor = System.Drawing.Color.Red;
        }
    }

    protected void Login1_LoggedIn(object sender, EventArgs e) {
        Dictionary<string, string> ccData = new Dictionary<string, string>();
        ccData["ccFirstname"] = firstName.Text;
        ccData["ccLastname"] = lastName.Text;
        ccData["ccType"] = creditCardType.SelectedValue;
        ccData["ccNumber"] = creditCardNumber.Text;
        ccData["ccExpiredMonth"] = expDateMonth.SelectedValue;
        ccData["ccExpiredYear"] = expDateYear.SelectedValue;
        ccData["ccVerificationNumber"] = cvv2Number.Text;
        ccData["ccAddress1"] = address1.Text;
        ccData["ccAddress2"] = address2.Text;
        ccData["ccCity"] = city.Text;
        ccData["ccState"] = state.Value;
        ccData["ccZipcode"] = Zip.Text;
        Session["CreditCardInfo"] = ccData;
    }

    [System.Web.Services.WebMethod]
    public static string CheckUserName(string args) {

        string returnValue = "Error";
        string conString = ConfigurationManager.ConnectionStrings["MyZuponsConnectionString2"].ConnectionString;
        SqlConnection sqlConn = new SqlConnection(conString);
        try {
            SqlCommand sqlCmd = new SqlCommand("CheckUserName2", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@User_Name", args.Trim());
            sqlConn.Open();
            int success = int.Parse((sqlCmd.ExecuteScalar().ToString()));
            if (success == 1) {
                returnValue = "<img src='Images/n.png'><font color='#cc0000'><b>'" + args + "'</b> is already in use.</font></img>";
            } else if (success == 0) {
                returnValue = "Available";
            }
        } catch (Exception ex) {

        } finally {

        }

        return returnValue;
    }
    protected void lnkbtnCancel_Click(object sender, EventArgs e) {
        Session["DealID"] = GetDealID();
        if (Session["DealID"] != null) {
            Response.Redirect("~/Default.aspx?DealID=" + Session["DealID"].ToString());
        }
    }
    protected void txtQuantity_TextChanged(object sender, EventArgs e) {
        try {
            if (txtQuantity.Text.Trim() != "") {
                if (IsPostBack) {
                    divAuthentication.Hide();
                }
                var quantity = new DealesDataContext();
                var TotalQtyQuery = quantity.Select_OrderByDealID(Convert.ToInt32(Session["DealID"]));
                foreach (var i in TotalQtyQuery) {
                    int bought = Convert.ToInt32(i.Total);
                    var query2 = new DealesDataContext();
                    var CheckQtyQuery = query2.Select_MaxQtyFromDeal(Convert.ToInt32(Session["DealID"]));
                    int MaxQty = 0;
                    int LimitPerPerson = 0;
                    foreach (var j in CheckQtyQuery) {
                        MaxQty = Convert.ToInt32(j.MaxQty);
                        LimitPerPerson = Convert.ToInt32(j.limitperperson);

                    }
                    if (Convert.ToInt32(txtQuantity.Text) > LimitPerPerson) {
                        txtQuantity.Text = "1";
                        double Total = 0.0;
                        Total = Convert.ToDouble(txtQuantity.Text) * Convert.ToDouble(lblPrice.Text);
                        lblTotalPrice.Text = System.Math.Round(double.Parse(Total.ToString()), 2).ToString();
                        lblYourTotal.Text = System.Math.Round(double.Parse(Total.ToString()), 2).ToString();
                        errmsg2.InnerText = "The maximum allowed quantity is " + LimitPerPerson;
                        Session["Quantity"] = txtQuantity.Text;
                        Session["TotalPrice"] = lblTotalPrice.Text;
                        FillCrdeitAmount();
                        return;
                    }
                    if (Convert.ToInt32(txtQuantity.Text) + bought > MaxQty) {
                        txtQuantity.Text = "";
                        txtQuantity.Text = "1";
                        double Total = 0.0;
                        Total = Convert.ToDouble(txtQuantity.Text) * Convert.ToDouble(lblPrice.Text);
                        lblTotalPrice.Text = System.Math.Round(double.Parse(Total.ToString()), 2).ToString();
                        lblYourTotal.Text = System.Math.Round(double.Parse(Total.ToString()), 2).ToString();
                        Session["Quantity"] = txtQuantity.Text;
                        Session["TotalPrice"] = lblTotalPrice.Text;
                        errmsg2.InnerText = "The maximum allowed quantity for deal is " + MaxQty;
                    } else {
                        errmsg2.InnerText = "";
                        double Total = 0.0;
                        Total = Convert.ToDouble(txtQuantity.Text) * Convert.ToDouble(lblPrice.Text);
                        lblTotalPrice.Text = System.Math.Round(double.Parse(Total.ToString()), 2).ToString();
                        lblYourTotal.Text = System.Math.Round(double.Parse(Total.ToString()), 2).ToString();
                        Session["Quantity"] = txtQuantity.Text;
                        Session["TotalPrice"] = lblTotalPrice.Text;
                    }
                }
                FillCrdeitAmount();
            } else {
                errmsg2.InnerText = "";
                txtQuantity.Text = "1";
                double Total = 0.0;
                Total = Convert.ToDouble(txtQuantity.Text) * Convert.ToDouble(lblPrice.Text);
                lblTotalPrice.Text = System.Math.Round(double.Parse(Total.ToString()), 2).ToString();
                lblYourTotal.Text = System.Math.Round(double.Parse(Total.ToString()), 2).ToString();
                Session["Quantity"] = txtQuantity.Text;
                Session["TotalPrice"] = lblTotalPrice.Text;
                FillCrdeitAmount();
            }

        } catch {
            txtQuantity.Text = "";
            txtQuantity.Text = "1";
            errmsg2.InnerText = "Digit only";
        }
    }
    protected void lnkBtnGift_Click(object sender, EventArgs e) {
        txtTo.Text = "";
        txtToEmail.Text = "";
        txtToEmail.Enabled = true;
        txtMessage.Text = "";
        rbtnDelivery.SelectedValue = "0";
        divAuthentication.Show();
    }
    protected void btnGiftSave_Click(object sender, EventArgs e) {
        if (rbtnDelivery.SelectedValue == "0") {
            if (txtToEmail.Text == "") {
                lblGiftErr.Text = "To Email is required.";
                return;
            }

        }
        DataTable dtGift = new DataTable();
        dtGift.Columns.Add("To");
        dtGift.Columns.Add("From");
        dtGift.Columns.Add("Message");
        dtGift.Columns.Add("Delivery");
        dtGift.Columns.Add("EmailTo");
        DataRow dr = dtGift.NewRow();
        dtGift.Rows.Add(dr);
        dtGift.Rows[0]["To"] = txtTo.Text.ToString();
        dtGift.Rows[0]["From"] = txtFrom.Text.ToString();
        dtGift.Rows[0]["Message"] = txtMessage.Text.ToString();
        dtGift.Rows[0]["Delivery"] = rbtnDelivery.SelectedValue.ToString();
        dtGift.Rows[0]["EmailTo"] = txtToEmail.Text.ToString();
        Session["dtGift"] = dtGift;
        lblGiftFor.Text = "<b>Gift For:</b> " + txtTo.Text;
        EditGift.Visible = true;
        SaveGift.Visible = false;
        divAuthentication.Hide();

    }
    protected void rbtnDelivery_SelectedIndexChanged(object sender, EventArgs e) {
        if (rbtnDelivery.SelectedValue == "1") {
            txtToEmail.Enabled = false;
            txtToEmail.Text = "";
            lblGiftErr.Text = "";
        } else
            txtToEmail.Enabled = true;
    }
    protected void lnkbtnEditGift_Click(object sender, EventArgs e) {
        divAuthentication.Show();
        DataTable dtGift = (DataTable)Session["dtGift"];
        txtTo.Text = dtGift.Rows[0]["To"].ToString();
        txtFrom.Text = dtGift.Rows[0]["From"].ToString();
        txtMessage.Text = dtGift.Rows[0]["Message"].ToString();
        txtToEmail.Text = dtGift.Rows[0]["EmailTo"].ToString();
        rbtnDelivery.SelectedValue = dtGift.Rows[0]["Delivery"].ToString();
    }
    protected void imgGiftCancel_Click(object sender, ImageClickEventArgs e) {
        divAuthentication.Hide();
        Session["dtGift"] = null;
        EditGift.Visible = false;
        SaveGift.Visible = true;
    }
    protected void Page_Prerender(object sender, EventArgs e) {
        Int32 cnt = 0;
        expDateYear.Items.Clear();
        for (cnt = DateTime.Today.Year; cnt <= DateTime.Today.Year + 10; cnt++) {
            expDateYear.Items.Add(new ListItem(cnt.ToString(), cnt.ToString()));
        }
        expDateYear.SelectedValue = DateTime.Today.Year.ToString();
    }
    protected void rbtnPaymentType_SelectedIndexChanged(object sender, EventArgs e) {
        if (rbtnPaymentType.SelectedValue == "0") {
            //PaypalTable.Visible = false;
            CrditeCardTable.Visible = true;
            firstName.Text = "";
            lastName.Text = "";
            creditCardType.SelectedValue = "Visa";
            creditCardNumber.Text = "";
            expDateMonth.SelectedValue = "1";
            expDateYear.SelectedValue = DateTime.Now.Year.ToString();
            cvv2Number.Text = "";
            address1.Text = "";
            address2.Text = "";
            city.Text = "";
            state.Value = "CA";
            Zip.Text = "";
            PayButton.Text = "Submit";
        } else {
            //PaypalTable.Visible = true;
            CrditeCardTable.Visible = false;
            //Name.Text = "";
            //Street.Text = "";
            //paypal_City.Text = "";
            //Select1.Value = "CA";
            //paypal_ZipCode.Text = "";
            PayButton.Text = "Continue";
        }
    }
    private bool isValidCreditCard(string type, string ccnum) {
        string regExp = "";

        if (type == "Visa")
            regExp = "^[4]([0-9]{15}$|[0-9]{12}$)";
        else if (type == "MasterCard")
            regExp = "^[5][1-5][0-9]{14}$";
        else if (type == "Discover")
            regExp = "^6011-?\\d{4}-?\\d{4}-?\\d{4}$";
        else if (type == "Diners Club")
            regExp = "(^30[0-5][0-9]{11}$)|(^(36|38)[0-9]{12}$)";
        else if (type == "American Express")
            regExp = "^[34|37][0-9]{14}$";
        else if (type == "enRoute")
            regExp = "^(2014|2149)[0-9]{11}$";
        else if (type == "JCB")
            regExp = "(^3[0-9]{15}$)|(^(2131|1800)[0-9]{11}$)";

        if (!System.Text.RegularExpressions.Regex.IsMatch(ccnum, regExp))
            return false;

        string[] tempNo = ccnum.Split('-');
        ccnum = String.Join("", tempNo);

        int checksum = 0;
        for (int i = (2 - (ccnum.Length % 2)); i <= ccnum.Length; i += 2) {
            checksum += Convert.ToInt32(ccnum[i - 1].ToString());
        }

        int digit = 0;
        for (int i = (ccnum.Length % 2) + 1; i < ccnum.Length; i += 2) {
            digit = 0;
            digit = Convert.ToInt32(ccnum[i - 1].ToString()) * 2;
            if (digit < 10) { checksum += digit; } else { checksum += (digit - 9); }
        }
        if ((checksum % 10) == 0)
            return true;
        else
            return false;

    }
    protected void PayButton_Click(object sender, EventArgs e) {
        Session["itemamount"] = System.Math.Round(Convert.ToDouble(lblTotalPrice.Text), 2);
        if (ViewState["CreditZero"] == null) {
            if (rbtnPaymentType.SelectedValue == "0") {
                if (isValidCreditCard(creditCardType.SelectedItem.Text, creditCardNumber.Text)) {
                    if (Session["username"] == null) {
                        string Message = SaveUserInfo();
                        if (Message == "Fail") {

                            return;
                        }
                    }
                    savedataforPayment();
                } else {
                    lblcreditCardNumber.ForeColor = System.Drawing.Color.Red;
                    lblErrormessage.Text = "Please verify the highlighted fields.";
                    return;
                }
            } else {
                if (Session["username"] == null) {
                    string Message = SaveUserInfo();
                    if (Message == "Fail") {
                        return;
                    }
                }
                savedataforpaypalPayment();
            }
        } else {
            DataTable dtTemp = new DataTable();
            dtTemp = null;
            Session["dtTemp"] = dtTemp;
            Response.Redirect("Receipts.aspx?CreditUsed=1");

        }

    }
    protected void savedataforPayment() {
        Global.is3token = true;
        Session["stage"] = "SandBox";
        SetProfile.SessionProfile = SetProfile.CreateAPIProfile(Constants.API_USERNAME, Constants.API_PASSWORD, Constants.API_SIGNATURE, "", "", "", "", "SandBox", "");
        PayPalAPI api = new PayPalAPI();
        int expMonth = int.Parse(expDateMonth.SelectedValue.ToString());
        int expYear = int.Parse(expDateYear.SelectedValue.ToString());
        basepage.PayPalResponse = api.DoDirectPayment(
            Convert.ToString(Session["TotalPrice"]),
             lastName.Text.ToString(),
               firstName.Text.ToString(),
              address1.Text.ToString(),
              address2.Text.ToString(),
              city.Text.ToString(),
              state.Value.ToString(),
              Zip.Text.ToString(),
               creditCardType.Text.ToString(),
               creditCardNumber.Text.ToString(),
              cvv2Number.Text.ToString(),
               expMonth,
               expYear, PaymentActionCodeType.Authorization, Convert.ToInt32(Session["Quantity"]));
        DataTable dtTemp = new DataTable();
        dtTemp.Columns.Add("address1");
        dtTemp.Columns.Add("address2");
        dtTemp.Columns.Add("city");
        dtTemp.Columns.Add("state");
        dtTemp.Columns.Add("Zip");
        dtTemp.Columns.Add("CCNo");
        DataRow dr = dtTemp.NewRow();
        dtTemp.Rows.Add(dr);
        dtTemp.Rows[0]["address1"] = address1.Text.ToString();
        dtTemp.Rows[0]["address2"] = address2.Text.ToString();
        dtTemp.Rows[0]["city"] = city.Text.ToString();
        dtTemp.Rows[0]["state"] = state.Value.ToString();
        dtTemp.Rows[0]["Zip"] = Zip.Text.ToString();
        dtTemp.Rows[0]["CCNo"] = creditCardNumber.Text.Substring(creditCardNumber.Text.Length - 4);
        Session["dtTemp"] = dtTemp;
        //Response.Redirect(Session["HttpsPath"].ToString() + "/Receipts.aspx");
        Response.Redirect("Receipts.aspx");
    }
    protected void savedataforpaypalPayment() {
        Global.is3token = true;
        Session["stage"] = "SandBox";
        SetProfile.SessionProfile = SetProfile.CreateAPIProfile(Constants.API_USERNAME, Constants.API_PASSWORD, Constants.API_SIGNATURE, "", "", "", "", "SandBox", "");
        basepage.PaymentAction = (PaymentActionCodeType)Enum.Parse(typeof(PaymentActionCodeType), "Authorization");
        Session["setecrequest"] = null;
        Hashtable requesthash = new Hashtable();
        requesthash.Add("currency", ((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), "USD")));
        requesthash.Add("NAME", "");
        requesthash.Add("STREET", "");
        requesthash.Add("CITY", "");
        requesthash.Add("STATE", "");
        requesthash.Add("COUNTRYCODE", "US");
        requesthash.Add("ZIP", "");
        requesthash.Add("L_AMT0", Session["TotalPrice"].ToString());
        requesthash.Add("L_QTY0", Session["Quantity"].ToString());
        requesthash.Add("L_NAME0", "Deal");
        Session["setecrequest"] = requesthash;
        DataTable dtTemp = new DataTable();
        dtTemp.Columns.Add("address1");
        dtTemp.Columns.Add("address2");
        dtTemp.Columns.Add("city");
        dtTemp.Columns.Add("state");
        dtTemp.Columns.Add("Zip");
        dtTemp.Columns.Add("CCNo");
        DataRow dr = dtTemp.NewRow();
        dtTemp.Rows.Add(dr);
        dtTemp.Rows[0]["address1"] = "";
        dtTemp.Rows[0]["address2"] = "";
        dtTemp.Rows[0]["city"] = "";
        dtTemp.Rows[0]["state"] = "";
        dtTemp.Rows[0]["Zip"] = "";
        dtTemp.Rows[0]["CCNo"] = "";
        Session["dtTemp"] = dtTemp;
        //Response.Redirect(Session["HttpsPath"].ToString() + "/ReviewOrder.aspx?");
        Response.Redirect("ReviewOrder.aspx?");
    }
    public string SaveUserInfo() {
        try {
            TextBox FullName = txtName;
            TextBox Email = txtEmail;
            TextBox Password = txtPassword;
            Label Msg = lblErr;
            MembershipCreateStatus S;
            MembershipUser newUser = Membership.CreateUser(
              Email.Text,
              Password.Text,
              Email.Text,
              "Your name?",
              FullName.Text,
              true,
              out S);

            Msg.Text = verifyStatus(S);
            var UserID = newUser.ProviderUserKey; Session["username"] = Email.Text;
            System.Web.Security.Roles.AddUserToRole(Email.Text, "user");
            FormsAuthentication.SetAuthCookie(Email.Text, false);
            //try
            //{

            //    System.Collections.Specialized.ListDictionary replacements = new System.Collections.Specialized.ListDictionary();
            //    replacements.Add("<%UserName%>", Email.Text);
            //    replacements.Add("<%FullName%>", FullName.Text);
            //    replacements.Add("<%Email%>", Email.Text);

            //    System.Net.Mail.MailMessage confirmation = Mailer.CreateMessage(new System.Web.UI.Control() as WebControl, Mailer.MessageTemplate.NewUserRegistrationConfirmation, replacements, Email.Text, "Your Zupons Registration");
            //    Mailer.InternalSend(confirmation, false);
            //}
            //catch
            //{
            //    Msg.Text = "Registration Successfull but email is not valid.. So Can't processes the order.";
            //}

            string strData = FullName.Text;
            char[] splitChar = new char[1];
            splitChar[0] = ' ';
            String[] col = strData.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);
            string FName = col[0];
            string LName = "";
            if (col.Count() > 1) {
                FName = col[0];
                LName = col[1];
            }
            string Address = null;
            string City = null;
            string State = null;
            string ZipCode = null;
            string Phone_Home = null;
            System.Data.Linq.Binary UserImage = null;
            string Phone_Mob = null;
            string Phone_Off = null;
            string Fax = null;
            string CardHolderName = null;
            string CardNumber = null;
            string BillingAddress = null;
            string SecurityCode = null;
            string City2 = null;
            string State2 = null;
            string ExpirationDate = "1/1/1900 12:00:00 AM";
            string PostalCode = null;
            bool Policy = true;
            var reg = new DealesDataContext();
            var RegisterQuery = reg.Insert_UserDetails(Convert.ToString(UserID), FName, LName, Address, City, State, ZipCode, UserImage, Phone_Home, Phone_Mob, Phone_Off, Fax, Convert.ToString(UserID), CardHolderName, Convert.ToInt64(CardNumber), BillingAddress, Convert.ToInt64(SecurityCode), City2, State2, Convert.ToDateTime(ExpirationDate), PostalCode, Policy);
            if (Session["ReferUserID"] != null) {
                var ReferUser = reg.Insert_ReferUser(new Guid(Convert.ToString(UserID)), new Guid(Convert.ToString(Session["ReferUserID"])), Convert.ToInt32(Session["DealID"]));

            }
            return "Success";
        } catch (Exception ex) {
            return "Fail";
        }

    }
    protected IEnumerable currencyCodeTypeDataSource {
        get {
            return Util.SupportedCurrencies();
        }
    }
    public string verifyStatus(MembershipCreateStatus status) {
        switch (status) {
            case MembershipCreateStatus.DuplicateUserName:
                return "Username already exists. Please enter a different user name.";

            case MembershipCreateStatus.DuplicateEmail:
                return "A username for that e-mail address already exists. Please enter a different e-mail address.";

            case MembershipCreateStatus.InvalidPassword:
                return "The password provided is invalid. Please enter a valid password value.";

            case MembershipCreateStatus.InvalidEmail:
                return "The e-mail address provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidAnswer:
                return "The password retrieval answer provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidQuestion:
                return "The password retrieval question provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidUserName:
                return "The user name provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.ProviderError:
                return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

            case MembershipCreateStatus.UserRejected:
                return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

            case MembershipCreateStatus.Success:
                return "Registeration Successfull";

            default:
                return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
        }
    }
    protected string TransactionID {
        get {
            return this.Request.QueryString.Get(Constants.TRANSACTIONID_PARAM);
        }
    }
    public override void DataBind() {
        if (this.TransactionID != null) {
            PayPalAPI api = new PayPalAPI();
            basepage.PayPalResponse = api.GetTransactionDetails(this.TransactionID);
        }
        base.DataBind();
    }
    protected override void OnPreRender(EventArgs e) {
        base.OnPreRender(e);
        this.DataBind();
    }
    protected void cvv2Number_TextChanged(object sender, EventArgs e) {
        try {
            if (cvv2Number.Text.Trim() != "") {
                int i = Convert.ToInt32(cvv2Number.Text);
                errmsg1.InnerText = "";
            }
        } catch {
            cvv2Number.Text = "";
            errmsg1.InnerText = "Digit only";
        }
    }
}
